package com.team.order.task;

import com.team.order.domain.Order;
import com.team.order.mapper.AppOrderMapper;
import com.team.order.utils.PaymentUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单超时自动取消任务
 * @author 梁国瑞
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OrderTimeoutTask {
    
    private final AppOrderMapper appOrderMapper;
    private final PaymentUtil paymentUtil;
    
    /**
     * 每5分钟执行一次，取消超时未支付的订单
     * 超时时间：30分钟
     */
    @Scheduled(fixedRate = 300000) // 5分钟 = 300000毫秒
    public void cancelTimeoutOrders() {
        try {
            log.info("开始执行订单超时自动取消任务");
            
            // 计算超时时间（30分钟前）
            LocalDateTime timeoutTime = LocalDateTime.now().minusMinutes(30);
            
            // 查询超时未支付订单
            List<Order> timeoutOrders = appOrderMapper.selectTimeoutOrders(timeoutTime);
            
            if (timeoutOrders.isEmpty()) {
                log.info("没有超时未支付的订单");
                return;
            }
            
            log.info("发现{}个超时未支付订单，开始取消", timeoutOrders.size());
            
            // 批量取消超时订单
            for (Order order : timeoutOrders) {
                try {
                    // 使用模拟支付失败来取消订单
                    boolean success = paymentUtil.simulatePaymentFail(order.getOrderNo());
                    if (success) {
                        log.info("成功取消超时订单，订单号：{}", order.getOrderNo());
                    } else {
                        log.error("取消超时订单失败，订单号：{}", order.getOrderNo());
                    }
                } catch (Exception e) {
                    log.error("取消超时订单异常，订单号：{}", order.getOrderNo(), e);
                }
            }
            
            log.info("订单超时自动取消任务执行完成");
        } catch (Exception e) {
            log.error("订单超时自动取消任务执行异常", e);
        }
    }
} 